import axios, {AxiosInstance, AxiosResponse} from "axios";
import {ElMessage} from "element-plus";
export class Request {
    public static axiosInstance: AxiosInstance

    // 创建axios实例并初始化拦截器
    public static init() {
        this.axiosInstance = axios.create({
            baseURL: '',
            timeout: 6000
        })
        this.initInterceptors()
        return axios
    }
    // 初始化拦截器
    public static initInterceptors() {
        // 设置post请求头
        this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
        // 响应拦截器
        this.axiosInstance.interceptors.response.use(
            (response: AxiosResponse) => {
                if(response.status === 200) {
                    return response
                }else {
                    Request.errorHandle(response)
                    return response
                }
            },
            (error:any) => {
             const {response} = error
             if(response) {
                 Request.errorHandle(response)
                 return Promise.reject(response.data)
             }else {
                 ElMessage.warning('网络连接异常，请稍后再试')
             }
            }
        )
    }

    // 错误响应回调
    private static errorHandle(res: any) {
        switch (res.status) {
            case 401:
                break;
            case 403:
                break;
            case 404:
                ElMessage.error('请求的资源不存在')
                break;
            default:
                ElMessage.warning('连接错误')
        }
    }
}
